﻿using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
using System.Reflection;

namespace OrderApi.Helpers
{
    public class SwaggerOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            // 从方法中获取摘要信息
            var methodInfo = context.MethodInfo;
            if (methodInfo == null) return;

            var summary = methodInfo.GetCustomAttribute<System.ComponentModel.DescriptionAttribute>()?.Description;
            if (string.IsNullOrEmpty(summary))
            {
                summary = methodInfo.GetCustomAttribute<System.ComponentModel.DescriptionAttribute>()?.Description;
            }

            if (!string.IsNullOrEmpty(summary))
            {
                operation.Summary = summary;
            }

            // 设置默认响应
            if (!operation.Responses.Any(r => r.Key == "200"))
            {
                operation.Responses.Add("200", new OpenApiResponse
                {
                    Description = "请求成功"
                });
            }
        }
    }

    public class LastModifiedDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Info.Version = $"v1 ({DateTime.Now:yyyy-MM-dd HH:mm})";
        }
    }
}
